package com.tt.payee.filter.webFliters;

import com.tt.payee.business.BusinessException;
import com.tt.payee.business.BusinessStatus;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：Tang
 * @date ：Created in 2020/8/19 14:12
 * @description：
 * @modified By：
 * @version: $
 */
@Component
public class CorsFilter implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if(CorsUtils.isCorsRequest(request)){
            response.setHeader("Access-Control-Allow-Origin", "Origin");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "1800");
            response.setHeader("Access-Control-Allow-Headers", "access_token,authorization,content-type,platform,request_token");
            response.setHeader("Access-Control-Expose-Headers", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            System.out.println("我是在DispatcherServlet之前执行的方法");
            System.out.println("asdasdasd");

            if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {

                throw new BusinessException(BusinessStatus.ILLEGAL_REQUEST);
            }
        }
        return true;
    }

}
